<?php
function generateMessageQuery($msg_from,$msg_to,$subject,$body,$reference_type="", $reference_detail_array="", $parent_message_id="", $message_status="act")
        {
	global $sql, $gen_message_details_table;
        $message["msg_from"]=$msg_from;
        $message["msg_to"]=$msg_to;
        $message["subject"]=$subject;
        $message["message_body"]=$body;
        if($reference_type)
                $message["reference_type"]=$reference_type;
        if($reference_detail_array)
                {
                $new_reference_detail_array="";
                foreach($reference_detail_array as $reference_detail => $company_id)
                        {
                        if (count($reference_detail_array) ==1)   //if only one item end the query
                                {
                                $new_reference_detail_array.="{".$reference_detail.",".$company_id."}";
                                }
                        else         //otherwise
                                {
                                $new_reference_detail_array.="{".$reference_detail.",".$company_id."},";
                                }
                        //  and removes the first value in the array
                        array_shift($reference_detail_array);
                        }
               $message["reference_detail"]="{".$new_reference_detail_array."}";
                }
        if($parent_message_id)
                $message["parent_message_id"]=$parent_message_id;
         if($message_status)
                 $message["message_status"]=$message_status;
	$sql->table=$gen_message_details_table;
	$sql->column=$message;
	$sql->generateInsertQuery();
        $message_query=$sql->query;
	return $message_query;
        }
//
// //*******************************************************
// // created on 07/04/2003, created by S.Gnanavel
// // Purpose:
// //	fetches the privileges of this user with
// // 	different companies
// // Output Format:
// //	privilege[company_id][privilege_desc]=permission
// //*******************************************************/
//
function getPrivilege($user_id)
	{
	global $db;
	$db->query="SELECT smc.company_id, sui.user_type_id FROM $sys_user_info sui JOIN $sys_master_relationship smr ON sui.relationship_id=smr.relationship_id JOIN $sys_master_company smc ON smr.partner_id=smc.company_id WHERE sui.user_id='$user_id';"; 
	$db->runQuery();

	$arrays=$db->returnArrays();
	for ($i=0;$i<count($arrays);$i++)
		{
		$user_type_id=$arrays[$i]["user_type_id"];
		$company_id=$arrays[$i]["member_id"];
		$db->query="select smp.data_category_desc[1] as privilege_desc, sutp.permission from $sys_master_privilege smp JOIN $sys_user_type_privilege sutp ON smp.privilege_id=sutp.privilege_id where user_type_id='$user_type_id';";
		$db->runQuery();
		$arrays1=$db->returnArrays();
		for ($j=0;$j<count($arrays1);$j++)
			{
			$privilege_desc=$arrays1[$j]["privilege_desc"];
			$privilege[$company_id][$privilege_desc]=$arrays1[$j]["permission"];
			}
		}
	return $privilege;
	}

 function getPreferences($type="default",$value="")
 	{
 	global $db,$sql,$LC;
	global $sys_master_preferences, $sys_company_preferences, $gen_user_preferences;

 	switch ($type)
 		{
 		case "default":
			$sql->table = $sys_master_preferences;
			$sql->column=array("preference_desc@$LC as \"Preference Name\"","default_values as \"Values\"");
			$sql->generateSelectQuery();
 			break;
 		case "member":
			$sql->table=$sys_company_preferences." scp";
			$sql->column = array("smp.preference_desc@$LC as \"Preference Name\"","scp.preferred_values as \"Values\"");
			$sql->join_condition = " inner join $sys_master_preferences smp on smp.preference_id=scp.preference_id";
			$sql->generateSelectQuery();
 			break;
 		case "user":
			$sql->table=$gen_user_preferences." gup";
			$sql->column = array("smp.preference_desc@$LC as \"Preference Name\"","gup.preferred_values as \"Values\"");
			$sql->join_condition = " inner join $sys_master_preferences smp on smp.preference_id = gup.preference_id and gup.user_id = $value";
			$sql->generateSelectQuery();
 			break;
 		}
	$db->query=$sql->query;
 	$db->runQuery();
 	$preference_array=$db->returnArrays();
 	if($preference_array)
 		{
 		for($i=0;$i<count($preference_array);$i++)
 			{
 			$name=$preference_array[$i]["Preference Name"];
 			$value=$preference_array[$i]["Values"];
 			$preferences[$name]=$value;
 			}
 		return $preferences;
 		}
 	}

function getUserId($login_name)
	{
	global $db,$sys_master_user;
	$login_name=strtolower($login_name);
	$db->query="select user_id from sys_master_user where lower(login_name) = '$login_name';";
	$db->runQuery();
	$user_array=$db->returnArrays();

	return $user_array[0]["user_id"];
	}

function getMemberId($user_id)
	{
	global $db;
	$db->query="select smr.partner_id from $sys_user_info sui JOIN $sys_master_relationships smr ON sui.relationship_id=smr.relationship_id where sui.user_id=$user_id;";
	$db->runQuery();
	$member_array=$db->returnArrays();
	return $member_array[0]["member_id"];
	}

function getUserTypeId($user_id,$member_id)
	{
	global $db;
	$db->query="select user_type_id from $sys_user_info sui JOIN $sys_master_relationships smr ON sui.relationship_id=smr.relationship_id where sui.user_id=$user_id and smr.partner_id=$member_id;";
	$db->runQuery();
	$member_user_details=$db->returnArrays();
	return $member_user_details[0]["user_type_id"];
	}
/*
Function Name: getUserInfo

Action: Fetches the details of an user

Created on : 29/09/2003

Author: S.Gnanavel
*/
function getUserInfo($column_name,$value)
	{
	/*class "cDatabase" should be instantiated*/
	global $db;
		
	/*Get the details of user from master_user against the information provided*/
	switch ($column_name)
		{
		case "user_id":
			$condition="smu.user_id='$value'";
			break;
		case "login_name":
			$condition="smu.login_name='$value'";
			break;
		}
		
	$db->query="select 
					smu.user_id, smu.login_name, smr.partner_id, smc.company_name, sui.user_type_id
				from 
					$sys_master_user smu JOIN $sys_user_info sui ON smu.user_id=sui.user_id JOIN $sys_master_relationship ON sui.relationship_id=smr.relationship_id JOIN $sys_master_company smc ON smr.partner_id=smc.company_id
				where 
					$condition;";
	$db->runQuery();
	$user_info_array["user_info"]=$db->returnArrays();
	$user_id=$user_info_array["user_info"][0]["user_id"];
	$member_id=$user_info_array["user_info"][0]["member_id"];
	
	if($user_id)
		{	
		// get the user type id's as array for the logged in user
		$db->query="select mur.member_id,mur.user_type_id from member_user_relation mur where mur.user_id=$user_id;";
		$db->runQuery();
		$user_type_id_array=$db->returnArrays();
		for($i=0;$i<count($user_type_id_array);$i++)
			{
			$user_member_id=$user_type_id_array[$i]["member_id"];
			$user_type_id=$user_type_id_array[$i]["user_type_id"];
			$user_type_details[$user_member_id][]=$user_type_id;
			}
		$user_info_array["user_type_id_array"]=$user_type_details;
		
		$db->query="select 
						product_category_id, activity_id 
					from
						member_product_details mpd, master_member mm 
					where
						mm.primary_product=mpd.product_details_id and 
						mm.member_id=$member_id;";
		$db->runQuery();
		$primary_product_details_array=$db->returnArrays();
		$user_info_array["primary_product_id"]=$primary_product_details_array[0]["product_category_id"];
		$user_info_array["primary_activity_id"]=$primary_product_details_array[0]["activity_id"];

		if($member_id > 1000)	
			{
			$user_info_array["privilege"]=getPrivilege($user_id);
			}

			// get the preferences for the user
		$default_preferences=getPreferences("default");
		$member_preferences=getPreferences("member",$member_id);
		$user_preferences=getPreferences("user",$user_id);

		$user_info_array["user_preferences"]=array_merge($default_preferences,$member_preferences,$user_preferences);
		}	
	return $user_info_array;
	}

// /*
// Function Name: addUser
// 
// Action: Adds an user to the database
// 
// Created on: 29/09/2003
// 
// Author: S.Gnanavel
// */		
function addUser($user_details_array)
	{
	/*Instantiate cDatabase class*/
	global $db,$sql,$sys_master_user;
	/*insert the following details of the user in master_user*/
	$db->query = "select nextval('sys_seq_mu_user_id') as user_id";
	$db->runQuery();
	$user_id_array = $db->returnArrays();
	
	$user_details["user_id"] = $user_id_array[0]["user_id"];
	$user_details["login_name"]=strtolower($user_details_array["login_name"]);
	$user_details["access_code"]=base64_encode(trim($user_details_array["password"]));

	$sql->table=$sys_master_user;
	$sql->column=$user_details;
	$sql->generateInsertQuery();
	$db->query=$sql->query;
	$db->runQuery();

	/*if successfully inserted in sys_master_user then get the user_id for the given login_name*/
	$user_id=getUserId($user_details_array["login_name"]);
		
	/*insert the following details into sys_user_info */
	$member_user_details["user_id"]=$user_id;
	$member_user_details["user_type_id"]=$user_details_array["user_type_id"];
	$member_user_details["relationship_id"]=$user_details_array["relationship_id"];
	$member_user_details["user_type_id"]=$user_details_array["user_type_id"];
	$member_user_details["first_name"]=$user_details_array["first_name"];
	$member_user_details["last_name"]=$user_details_array["last_name"];
	$member_user_details["initials"]=$user_details_array["initials"];
	$sql->table="sys_user_info";
	$sql->column=$member_user_details;
	$sql->generateInsertQuery();
	$db->query=$sql->query;
	$db->runQuery();

	$db->query="select privilege_id,permission from sys_user_type_privilege where user_type_id='".$user_details_array["user_type_id"]."';";
	$db->runQuery();
	$privilege_default=$db->returnArrays();
	
	$cnt=count($privilege_default);
	for($i=0;$i<$cnt;$i++)
	{
	$privelege_array["user_id"]=$user_id;
	$privelege_array["privilege_id"]=$privilege_default[$i]["privilege_id"];
	$privelege_array["permission"]=$privilege_default[$i]["permission"];
	$sql->table="sys_user_privilege";
	$sql->column=$privelege_array;
	$sql->generateInsertQuery();
	$db->query=$sql->query;
	$db->runQuery();
	}
	if($db->result)
		{
		/*if successfully inserted in sys_user_info then get the primary relation*/
// 		$db->query="select mu_relation_id from member_user_relation order by mu_relation_id desc limit 1;";
// 		$db->runQuery();
// 		$mur_array=$db->returnArrays();
// 		$mu_relation_id=$mur_array[0]["mu_relation_id"];

		/*Update users primary relation with the member in master user*/
// 		$db->query="update master_user set primary_relation=$mu_relation_id where user_id=$user_id;";
// 		$db->runQuery();

		/*Put an entry for this user in forum_users*/
// 		$db->query=generateInsertQuery("forum_users",array("user_id"=>"$user_id"));
// 		$db->runQuery();

		/*Put an entry for this user in user_info*/
//  		$db->query=generateInsertQuery("user_info",array("user_id"=>"$user_id"));
// 		$db->runQuery();
		
// 		$db->query="commit;";
// 		$db->runQuery();
		}

	if(!$db->result)
		{
		$add_user["error"]="Database error. Please try again later...";
		}
	/*return NULL if registration is success or return the corressponding error*/
	return $add_user;
	}
	
function addExistingUser($user_details)
	{
	global $db;

	$db->query="begin work;";
	$db->runQuery();

	$db->query=generateInsertQuery("member_user_relation",$user_details);
	$db->runQuery();

	$db->query="select mu_relation_id from member_user_relation order by mu_relation_id desc limit 1;";
	$db->runQuery();
	$mu_relation_array=$db->returnArrays();
	$mu_relation_id=$mu_relation_array[0]["mu_relation_id"];

	$user_id=$user_details["user_id"];
	$db->query="update master_user set primary_relation=$mu_relation_id where user_id=$user_id;";
	$db->runQuery();
	
	$db->query="commit;";
	$db->runQuery();

	}	

	
 //function addForumUser($user_id)
// 	{
// 	global $db;
// 	$user_details_array["user_id"]=$user_id;
// 	$user_details_array["member_id"]=1000;
// 	$user_details_array["user_type_id"]="ind";
// 	$db->query=generateInsertQuery("member_user_relation",$user_details_array);
// 	$db->runQuery();
// 	}
	
// A function to generate random alphanumeric passwords in PHP
// It expects to be passed a desired password length, but it
// none is passed the default is set to 8 (you can change this)
function generatePassword($length = 10)
	{
	// This variable contains the list of allowable characters
   	// for the password.  Note that the number 0 and the letter
   	// 'O' have been removed to avoid confusion between the two.
   	// The same is true of 'I' and 1
   	$allowable_characters ='abcdefghefghijklmnopqrstuvwxyz0123456789_';

   	// We see how many characters are in the allowable list
   	$ps_len = strlen($allowable_characters);

   	// Max index of the characters allowed to stand and end the output.
   	$max_endpoint_ind = 25;

   	// 0-based index of the last char of the output
   	$last_char = $length - 1;

   	// Seed the random number generator with the microtime stamp
   	// (current UNIX timestamp, but in microseconds)
   	mt_srand((double)microtime() * 1000000);

   	// Declare the password as a blank string.
   	$pass = "";

   	// Loop the number of times specified by $length
   	for($i = 0; $i < $length; $i++)
		{
		// Each iteration, pick a random character from the
		// allowable string and append it to the password.
		switch ($i)
			{
			case 0:
			case $last_char:
				$pass .= $allowable_characters{mt_rand(0,$max_endpoint_ind)};
				break;
			default:
				$pass .= $allowable_characters{mt_rand(0, $ps_len)};
			}
		}
	// Retun the password we've selected
   	return $pass;
	}

function getKarma()
	{
	global $db;
	
	if($_SESSION[guser_id])
		{
		$db->query="select karma from _100099.collab_forum_users where user_id=$_SESSION[guser_id]";
		$db->runQuery();
		$karma_array=$db->returnArrays();
		}
	return $karma_array[0]["karma"];
	}

function getMessageCount()
	{
	global $db;
	if($_SESSION[guser_id])
		{
		$db->query="select message_id from _100099.gen_message_details where msg_to=$_SESSION[guser_id] ";
		$db->runQuery();
		$msg_count_array=$db->returnArrays();
		}
	return count($msg_count_array);
	}

function redirect($path="../")
 	{
  	if(!$_SESSION["gcompany_id"])
  		{
  		header("Location:../$path"."users/login.php");
  		}
  	else
  		{

  		switch($_SESSION["gcompany_id"])
  			{
  			case 100002:
  				header("Location:$path"."admin/homepage.php");
  				break;

  			case $_SESSION["gcompany_id"] > 1000:
 				header("Location:$path"."users/homepage.php");
  				break;
  			}
 		}
 	}
?>
